package servlet;

import entity.FinancingProduct;
import service.FinancingProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;

@WebServlet("/add")
public class AddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");
        int risk = Integer.parseInt(request.getParameter("risk"));
        String income = request.getParameter("income");
        String saleStartingStr = request.getParameter("saleStarting");
        String saleEndStr = request.getParameter("saleEnd");
        String endStr = request.getParameter("end");

        FinancingProduct product = new FinancingProduct();
        product.setId(id);
        product.setRisk(risk);
        product.setIncome(income);
        product.setSaleStarting(Date.valueOf(saleStartingStr));
        product.setSaleEnd(Date.valueOf(saleEndStr));
        product.setEnd(Date.valueOf(endStr));

        FinancingProductService service = new FinancingProductService();
        boolean success = false;
        try {
            success = service.addProduct(product);
            if (success) {
                response.sendRedirect("queryAll");
            } else {
                response.sendRedirect("add.jsp?error=true");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendRedirect("error.jsp");
        }
    }
}
